package cn.cau.control;

import cn.cau.entity.*;
import cn.cau.service.*;
import cn.cau.utils.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
@Controller
public class CodeManageChangeController {
    @Autowired
    private CodeManageChangeService codeManageChangeService;
    @Autowired
    private CodeRuleService codeRuleService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BasicEnumService basicEnumService;
    @Autowired
    private CodeManageSearchService codeManageSearchService;
    @Autowired
    private NonEnumService nonEnumService;
    @Autowired
    private CommonUserService commonUserService;
    @Autowired
    private AuditingListService auditingListService;
    @Autowired
    private RuleCategoryService ruleCategoryService;
    /**
     * 可修改编码列表
     *
     * @return
     */
    @RequestMapping(value = "/codeChangeList", method = RequestMethod.GET)
    public ModelAndView codeChangeList(HttpSession session) {
        List<CodeRule> codeRules=null;
        if (session.getAttribute("userInfo") != null) {
            //如果用户登录
            CommonUser commonUser = (CommonUser) session.getAttribute("userInfo");
            codeRules = codeManageChangeService.showCodeRuleChangeList(commonUser.getUserId());
        }
        ModelAndView modelAndView = new ModelAndView();
        List<RuleCategory> ruleCategories=null;
        ruleCategories=ruleCategoryService.findAllRuleCategorys();
        modelAndView.addObject("ruleCategories",ruleCategories);
        modelAndView.addObject("codeRules", codeRules);
        modelAndView.setViewName("codeManage/codeChangeList");
        return modelAndView;
    }
    /**
     * 编码修改申请
     *
     * @return
     */
    @RequestMapping(value = "/codeChangeInfo", method = RequestMethod.GET)
    public ModelAndView codeChangeInfo(@RequestParam(value = "codeRuleId") int codeRuleId){
        ModelAndView modelAndView = new ModelAndView();
        boolean haveCodeNumber=codeManageChangeService.isCodeRuleHaveCodeNumber(codeRuleId);
        modelAndView.addObject("codeRule",codeRuleService.findCodeRuleById(codeRuleId));
        modelAndView.addObject("category",categoryService.findCategoryById(codeRuleService.findCodeRuleById(codeRuleId).getCategoryId()));
        modelAndView.addObject("basicEnumSums",basicEnumService.findBasicEnumSumByCodeRuleId(codeRuleId));
        modelAndView.addObject("nonEnums",nonEnumService.findNonEnumByCodeId(codeRuleId));
        modelAndView.addObject("creatorName",commonUserService.findCommonUserById(codeManageChangeService.findRecordByNewCodeRuleId(codeRuleId).getManageManId()).getUserName());
        if(haveCodeNumber){
            modelAndView.setViewName("codeManage/codeLimitedChangeInfo");
        }else{
            modelAndView.setViewName("codeManage/codeChangeInfo");
        }
        return modelAndView;
    }
    /**
     * 编码修改提交
     *
     * @return
     */
    @RequestMapping(value = "/codeChangeApplication", method = RequestMethod.POST)
    public ModelAndView codeChangeApply(
                                        HttpSession session,
                                        HttpServletRequest request,
                                        @RequestParam(value = "codeRuleId") int codeRuleId,
                                        @RequestParam(value = "code_names[]")List<String> code_names,
                                        @RequestParam(value = "code_categorys[]")List<String> code_categorys,
                                        @RequestParam(value = "code_nums[]")List<String> code_nums,
                                        @RequestParam(value = "details[]") ArrayList<String> details,
                                        @RequestParam(value = "manageContent") String manageContent,
                                        @RequestParam(value = "detailsname[]") ArrayList<String> detailsnames){
                                                ModelAndView modelAndView = new ModelAndView();
        //小类对象创建
        Category cg=new Category();
        cg.setCategoryId(0);
        cg.setRuleCategoryId(Integer.valueOf(request.getParameter("categoryOptions").toString()));
        cg.setCategory(request.getParameter("category"));
        String cgcategory=request.getParameter("categorydetail");
        if (cgcategory.length()==1){
            cgcategory=0+cgcategory;
        }
        cg.setDetails(cgcategory);
        int res=categoryService.insertCategory(cg);
        //规则对象创建
        CodeRule cr=new CodeRule();
        cr.setCodeRuleId(0);
        cr.setCategoryId(cg.getCategoryId());
        cr.setRuleCategoryId(Integer.valueOf(request.getParameter("categoryOptions").toString()));
        cr.setCodeCodeCount(Integer.valueOf(request.getParameter("codeCodeCount").toString()));
        cr.setCodeRuleName(request.getParameter("codeDesignName"));
        cr.setCodeRuleIntro(request.getParameter("codeDescribe"));
        cr.setSerialNumber(Integer.valueOf(request.getParameter("serial_number")));
        //设置categoryId
        cr.setCategoryId(cg.getCategoryId());
        cr.setCodeState(1);

        //codeRule入库
        res=codeRuleService.insertCodeRule(cr);
        Iterator it1 = code_names.iterator();
        Iterator it2 = code_categorys.iterator();
        Iterator it3 = code_nums.iterator();
        Iterator it4 = details.iterator();
        Iterator it5 = detailsnames.iterator();

        int count=0;
        while (it1.hasNext()){
            String code_name=it1.next().toString();
            String code_category=it2.next().toString();
            String code_num=it3.next().toString();
            String detail=it4.next().toString();
            String detailsname=it5.next().toString();
            //码段名称

            if(code_names.size()==1 ){
                while(it4.hasNext()){
                    detail=detail+","+it4.next();
                    detailsname=detailsname+","+it5.next();
                }
            }
            if (Integer.valueOf(code_category)==1){
                //枚举类
                count=count+1;
                String[] basicEnums=detail.split(",");
                String[] basicEnumsNames=detailsname.split(",");
                for (int i=0;i< basicEnums.length;i++){
                    BasicEnum bs=new BasicEnum();
                    bs.setCodeCodeId(count);
                    bs.setCodeRuleId(cr.getCodeRuleId());
                    bs.setBasicEnumeration(basicEnums[i]);
                    bs.setDetailsname(basicEnumsNames[i]);
                    bs.setDetails(code_name);
                    bs.setCodeLength(Integer.valueOf(code_num));
                    res=basicEnumService.insertBasicEnum(bs);
                }
            } else {
                //非枚举类
                count=count+1;
                NonEnum ne=new NonEnum();
                ne.setCodeCodeId(count);
                ne.setCodeRuleId(cr.getCodeRuleId());
                ne.setDetails(code_name);
                String upperLimit=detail.split(",")[0];
                String lowerLimit=detail.split(",")[1];
                ne.setUpperLimit(upperLimit);
                ne.setLowerLimit(lowerLimit);
                ne.setCodeLength(Integer.valueOf(code_num));
                res=nonEnumService.insertNonEnum(ne);
            }
        }


        //获取用户
        CommonUser commonUser = (CommonUser) session.getAttribute("userInfo");
        CodeRule codeRule=codeRuleService.findCodeRuleById(codeRuleId);
        codeRule.setCodeState(1);//设置为审核状态
        int result=codeRuleService.updateCodeRule(codeRule);

        if(result==1){
            //管理表
            CodeManageRecord codeManageRecord=new CodeManageRecord();
            codeManageRecord.setOldCodeRuleId(codeRuleId);
            codeManageRecord.setNewCodeRuleId(cr.getCodeRuleId());
            codeManageRecord.setManageOperation(0);
            codeManageRecord.setManageContent(manageContent);
            codeManageRecord.setManageManId(commonUser.getUserId());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            codeManageRecord.setApplyTime(df.format(new Date()));
            result=codeManageChangeService.submitCodeRuleChange(codeManageRecord);
        }
        result=result+1;
        modelAndView.addObject("result",result);
        modelAndView.setViewName("codeManage/codeManageIndex");
        return modelAndView;
    }
    @RequestMapping(value = "/codeDesignList", method = RequestMethod.GET)
    public ModelAndView codeDesignList(HttpSession session)  {
        List<CodeManageRecord> codeManageRecords=null;
        List<AuditingApplyRecord> records = new ArrayList<>();   //总待审核表
        if (session.getAttribute("userInfo") != null) {
            //如果用户登录
            CommonUser commonUser = (CommonUser) session.getAttribute("userInfo");
            codeManageRecords = codeManageSearchService.showCodeRuleManageList(commonUser.getUserId());
            for(CodeManageRecord apply : codeManageRecords){
                AuditingApplyRecord temp_record = new AuditingApplyRecord();
                int old_id = apply.getOldCodeRuleId(),new_id = apply.getNewCodeRuleId();
                CodeRule rule = new CodeRule();

                int op = apply.getManageOperation();
                if(op==0){
                    temp_record.setOperation("修改申请");
                }
                else if(op==1){
                    temp_record.setOperation("废除申请");
                }
                else{
                    temp_record.setOperation("设计申请");
                }

                if(op==1){
                    rule = auditingListService.getReluById(old_id);  //如果为废除申请，则对old_rule进行操作
                }
                else{
                    rule = auditingListService.getReluById(new_id);  //否则，对new_rule进行操作
                }

                temp_record.setResult(rule.getCodeState());
                temp_record.setIndex(apply.getCodeRuleManageId());
                temp_record.setReason(apply.getManageContent());
                temp_record.setOp(op);    //0代表修改，1代表设计，2代表废除
                temp_record.setState(rule.getCodeState());
                temp_record.setOldId(apply.getOldCodeRuleId());
                temp_record.setNewId(apply.getNewCodeRuleId());     //newId中存储申请对应的主表id
                temp_record.setDate(apply.getApplyTime());         //日期
                temp_record.setUserId(apply.getManageManId());       //申请人
                temp_record.setObjectName(rule.getCodeRuleName());  //获取名称
                //
                if(op==2)
                    records.add(temp_record);
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("records", records);
        modelAndView.setViewName("codeManage/codeManageList");
        return modelAndView;
    }
}